import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useUserStoreHook } from '@/store/modules/user.store';
import router from '@/router';
import { ElNotification } from 'element-plus';

const USER_TIMEOUT = 10 * 60 * 1000; // 10分钟 (毫秒)

export function useUserActivity() {
  let timeoutId: number | null = null;
  const lastActivityTime = ref<number>(Date.now());
  const isMonitoringActive = ref(false);

  // 判断当前路由是否为登录页等无需监测的页面
  const shouldMonitorActivity = () => {
    const currentPath = router.currentRoute.value?.path;
    // 在登录页、404、401、501等页面不进行活动监测
    const noMonitorPages = ['/login', '/404', '/401', '/501'];
    return !noMonitorPages.includes(currentPath || '');
  };

  // 重置超时计时器
  const resetTimeout = () => {
    if (timeoutId !== null) {
      window.clearTimeout(timeoutId);
    }

    // 检查是否应该启动监测
    if (!shouldMonitorActivity()) {
      isMonitoringActive.value = false;
      return;
    }

    lastActivityTime.value = Date.now();
    isMonitoringActive.value = true;
    
    timeoutId = window.setTimeout(() => {
      if (shouldMonitorActivity()) {
        handleUserTimeout();
      }
    }, USER_TIMEOUT);
  };

  // 处理用户超时
  const handleUserTimeout = () => {
    console.log('用户活动超时，执行登出操作');
    ElNotification({
      title: '提示',
      message: '由于长时间无操作，您已自动退出登录',
      type: 'info',
    });
    
    // 登出用户
    const userStore = useUserStoreHook();
    userStore.resetAllState();
    router.push('/login');
  };

  // 重置计时器（用户有活动时调用）
  const resetActivityTimer = () => {
    if (shouldMonitorActivity()) {
      resetTimeout();
    }
  };

  // 监听路由变化
  const handleRouteChange = () => {
    if (shouldMonitorActivity()) {
      resetTimeout();
    } else {
      // 如果进入无需监测的页面，停止监测
      if (timeoutId !== null) {
        window.clearTimeout(timeoutId);
        timeoutId = null;
      }
      isMonitoringActive.value = false;
    }
  };

  // 初始化活动监测
  const initActivityMonitoring = () => {
    // 监听用户活动事件
    const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click'];
    
    events.forEach(event => {
      document.addEventListener(event, resetActivityTimer, true);
    });

    // 监听路由变化
    router.afterEach(() => {
      handleRouteChange();
    });

    // 初始化超时计时器（如果当前页面需要监测）
    if (shouldMonitorActivity()) {
      resetTimeout();
    }
  };

  // 清理活动监测
  const cleanupActivityMonitoring = () => {
    if (timeoutId !== null) {
      window.clearTimeout(timeoutId);
    }

    // 移除事件监听器
    const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click'];
    
    events.forEach(event => {
      document.removeEventListener(event, resetActivityTimer, true);
    });
  };

  // 在组件挂载时开始监测
  onMounted(() => {
    initActivityMonitoring();
  });

  // 在组件卸载时清理
  onUnmounted(() => {
    cleanupActivityMonitoring();
  });

  return {
    resetActivityTimer,
    lastActivityTime,
    isMonitoringActive,
    USER_TIMEOUT
  };
}